#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
 #include <unistd.h>

//文件指针结构体
struct File
{
	int argc;
	const char**argv;
	int size;
}Fiile;
//1、创建无名信号量
//sem_t sem;
void *tesk1(void*arg);
void *tesk2(void*arg);
void Fopen(struct File*);//检测目标文件并返回源文件大小
/////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc,const char*argv[])
{
	struct File T1={argc,argv,0};
	if(argc!=3){printf("文件源缺失\n");return -1;}
	Fopen(&T1);
	//2、初始化无名信号量
	//sem_init(&sem,0,0);
	pthread_t p1,p2;
	if(pthread_create(&p1,NULL,tesk1,&T1)!=0){perror("创建失败:");return -1;}
	if(pthread_create(&p2,NULL,tesk2,&T1)!=0){perror("创建失败:");return -1;}
	printf("等待回收p1\n");
	pthread_join(p1,NULL);
	printf("等待回收p2\n");
	pthread_join(p2,NULL);
	return 0;
}
void Fopen(struct File* T1)
{
	printf("%s\n",T1->argv[1]);
	int F1=-1,F2=-1;
	if((F1=open(T1->argv[1],O_RDONLY))==-1||(F2=open(T1->argv[2],O_WRONLY|O_CREAT|O_TRUNC,0664))==-1){perror("打开文件失败");return;}
	T1->size=lseek(F1,0,SEEK_END);
	printf("打开文件成功,大小为：%d\n",T1->size);
	close(F1);
	close(F2);
	return;
}
void *tesk1(void*arg)
{
	struct File T1=*(struct File*)arg;
	int F1=-1,F2=-1,ret=-1,top=T1.size/2;
	printf("线程1文件为%s,,,%s\n,大小为%d\n\n",T1.argv[1],T1.argv[2],top);
	if((F1=open(T1.argv[1],O_RDONLY))==-1||(F2=open(T1.argv[2],O_WRONLY))==-1){perror("打开文件失败");return NULL;}
	lseek(F1,0,0);
	lseek(F2,0,0);
	char x;
	for(int i=1;i<=top;i++)
	{
		if(ret=read(F1,&x,1)>0)
		{
			if(write(F2,&x,1)!=1)
			{
				perror("拷贝失败");
				break;
			}
		}
		else
		{
			perror("读取失败");
			break;
		}
	}
	close(F1);
	close(F2);
	return NULL;
}
void *tesk2(void*arg)
{
	struct File T1=*(struct File*)arg;
	int F1=-1,F2=-1,ret=-1,top=T1.size-T1.size/2;
	printf("线程2文件为%s,,,%s\n,大小为%d\n\n",T1.argv[1],T1.argv[2],top);
	if((F1=open(T1.argv[1],O_RDONLY))==-1||(F2=open(T1.argv[2],O_WRONLY))==-1){perror("打开文件失败");return NULL;}
	lseek(F1,T1.size-T1.size/2,0);
	lseek(F2,T1.size-T1.size/2,0);
	char x;
	for(int i=1;i<=top;i++)
	{
		if(ret=read(F1,&x,1)>0)
		{
			if(write(F2,&x,1)!=1)
			{
				perror("拷贝失败");
				break;
			}

		}
		else
		{
			perror("读取失败");
			break;
		}
	}
	close(F1);
	close(F2);
	return NULL;
	
}
